<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.1.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="Thrift Thrift最初由Facebook研发，主要用于各个服务之间的RPC通信，支持跨语言，常用的语言比如C++，Java，Python，PHP，Ruby，Erlang，Perl，Haskell，C#，Cocoa，JavaScript，Node.js，SmallTalk and OCaml都支持。 Thrift是一个典型的CS（客户端/服务端）结构，客户端和服务端可以使用不同语言开发。既然">
<meta name="keywords" content="java,Netty">
<meta property="og:type" content="article">
<meta property="og:title" content="Netty-Apache Thrift介绍和使用">
<meta property="og:url" content="http://www.saily.top/2017/07/09/netty4/index.html">
<meta property="og:site_name" content="帆的博客">
<meta property="og:description" content="Thrift Thrift最初由Facebook研发，主要用于各个服务之间的RPC通信，支持跨语言，常用的语言比如C++，Java，Python，PHP，Ruby，Erlang，Perl，Haskell，C#，Cocoa，JavaScript，Node.js，SmallTalk and OCaml都支持。 Thrift是一个典型的CS（客户端/服务端）结构，客户端和服务端可以使用不同语言开发。既然">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2017-12-12T03:40:07.931Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Netty-Apache Thrift介绍和使用">
<meta name="twitter:description" content="Thrift Thrift最初由Facebook研发，主要用于各个服务之间的RPC通信，支持跨语言，常用的语言比如C++，Java，Python，PHP，Ruby，Erlang，Perl，Haskell，C#，Cocoa，JavaScript，Node.js，SmallTalk and OCaml都支持。 Thrift是一个典型的CS（客户端/服务端）结构，客户端和服务端可以使用不同语言开发。既然">



  <link rel="alternate" href="/atom.xml" title="帆的博客" type="application/atom+xml" />




  <link rel="canonical" href="http://www.saily.top/2017/07/09/netty4/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Netty-Apache Thrift介绍和使用 | 帆的博客</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">帆的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">扬帆起航</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.saily.top/2017/07/09/netty4/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="杨帆">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/img/photo/bug.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="帆的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Netty-Apache Thrift介绍和使用
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
                
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-07-09T10:58:58+08:00">7月 9 2017</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Netty/" itemprop="url" rel="index"><span itemprop="name">Netty</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Thrift"><a href="#Thrift" class="headerlink" title="Thrift"></a>Thrift</h1><ul>
<li>Thrift最初由Facebook研发，主要用于各个服务之间的RPC通信，<strong>支持跨语言</strong>，常用的语言比如C++，Java，Python，PHP，Ruby，Erlang，Perl，Haskell，C#，Cocoa，JavaScript，Node.js，SmallTalk and OCaml都支持。</li>
<li>Thrift是一个典型的CS（客户端/服务端）结构，客户端和服务端可以使用不同语言开发。既然客户端和服务端能使用不同的语言开发，那么一定就要有一种中间语言来关联客户端和服务端的语言，这种语言就是<strong>IDL（Interface Description L anguage）</strong>。</li>
<li>Thrift不支持无符号类型，因为很多变成语言不存在无符号类型，比如Java</li>
</ul>
<h2 id="Thrift数据类型"><a href="#Thrift数据类型" class="headerlink" title="Thrift数据类型"></a>Thrift数据类型</h2><ul>
<li>byte：有符号字节</li>
<li>i16：16位有符号整数</li>
<li>i32：32位有符号整数</li>
<li>i64：64位有符号整数</li>
<li>double：64位有符号整数</li>
<li>double：64位浮点数</li>
<li>string：字符串</li>
</ul>
<a id="more"></a>
<h2 id="Thrift容器类型"><a href="#Thrift容器类型" class="headerlink" title="Thrift容器类型"></a>Thrift容器类型</h2><ul>
<li>集合中的元素可以是除了service之外的任何类型，包括exception</li>
<li>list：一些列由T类型的数据组成的有序列表，元素可以重复</li>
<li>set：一系列由T类型的数据组成的无序集合，元素不可重复</li>
<li>map：一个字典结构，key为K类型，value为V类型，相当于Java中的HashMap</li>
</ul>
<h2 id="Thrift工作原理"><a href="#Thrift工作原理" class="headerlink" title="Thrift工作原理"></a>Thrift工作原理</h2><ul>
<li>如何实现多语言之间的通信？<ul>
<li>数据传输使用socket（多重语言均支持），数据再已特定的格式（string等）发送，接受方语言进行解析。</li>
<li>定义thrift的文件，由thrift文件（IDL）生成双方语言的接口、model，在生成的model以及接口中会有解码编码的代码</li>
</ul>
</li>
</ul>
<h3 id="结构体（struct）"><a href="#结构体（struct）" class="headerlink" title="结构体（struct）"></a>结构体（struct）</h3><ul>
<li><p>就像C语言一样，Thrift支持struct类型，目的就是将一些数据聚合在一起，方便传输管理。struct的定义形式如下：</p>
  <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">struct Prople &#123;</span><br><span class="line">	1:string name;</span><br><span class="line">	2:i32 age;</span><br><span class="line">	3:string gender;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="枚举"><a href="#枚举" class="headerlink" title="枚举"></a>枚举</h3><ul>
<li><p>枚举的定义形式和Java的Enum定义累死：</p>
  <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">enum Gender &#123;</span><br><span class="line">	MALE,</span><br><span class="line">	FEMALE</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="异常（exception）"><a href="#异常（exception）" class="headerlink" title="异常（exception）"></a>异常（exception）</h3><ul>
<li><p>Thrift支持自定义exception，规则与struct一样</p>
  <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">exception RequestException &#123;</span><br><span class="line">	1:i32 code;</span><br><span class="line">	2:string reasone;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="服务（service）"><a href="#服务（service）" class="headerlink" title="服务（service）"></a>服务（service）</h3><ul>
<li><p>Thrift定义服务相当于Java中创建Interface一样，创建的service经过代码生成命令之后就会生成客户端和服务端的框架代码。定义形式如下：</p>
  <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">service HelloWorldService &#123;</span><br><span class="line"> //service中定义的函数，相当于Java interface中定义的方法</span><br><span class="line"> string doAction(1:string name, 2:i32 age);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="类型定义"><a href="#类型定义" class="headerlink" title="类型定义"></a>类型定义</h3><ul>
<li><p>Thrift支持类似C++一样的typedef定义：</p>
  <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">typedef i32 int</span><br><span class="line">typedef i64 long</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="常量（const）"><a href="#常量（const）" class="headerlink" title="常量（const）"></a>常量（const）</h3><ul>
<li><p>thrift也支持常量定义，使用const关键字：</p>
  <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">const i32 MAX_RETRIES_TIME = 10</span><br><span class="line">const string MY_WEBSIZE = &quot;http://facebook.com&quot;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="命名空间"><a href="#命名空间" class="headerlink" title="命名空间"></a>命名空间</h3><ul>
<li><p>Thrift的命名空间相当于Java中的package的意思，主要目的是组织代码。thrift使用关键<code>namespace</code> 定义命名空间：</p>
<p>  <code>namespace java com.test.thrift.demo</code></p>
</li>
<li>格式是：namespace 语言名 路径</li>
</ul>
<h3 id="文件包含"><a href="#文件包含" class="headerlink" title="文件包含"></a>文件包含</h3><ul>
<li><p>Thrift支持文件包含，相当于C/C++中的include，Java中的import。使用关键字include定义：</p>
<p>  <code>include &quot;global.thrift&quot;</code></p>
</li>
</ul>
<h3 id="注释"><a href="#注释" class="headerlink" title="注释"></a>注释</h3><ul>
<li>Thrift注释方式支持shell风格的注释，支持C/C++风格的注释，即#和//开头的语句都当作注释，/**/包裹的语句也是注释。</li>
</ul>
<h3 id="可选与必选"><a href="#可选与必选" class="headerlink" title="可选与必选"></a>可选与必选</h3><ul>
<li><p>Thrift提供两个关键字required，optional，分别用于表示对应的字段是必填的还是可以选的</p>
  <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">struct People &#123;</span><br><span class="line">	1:required string name;</span><br><span class="line">	2:optional i32 age;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="生成代码"><a href="#生成代码" class="headerlink" title="生成代码"></a>生成代码</h3><ul>
<li>了解了如何定义thrift文件之后，我们需要用定义好的thrift文件生成我们需要的目标语言的源码</li>
<li>首先需要定义thrift接口描述文件</li>
<li>参见data.thrift</li>
</ul>
<p><strong>data.thrift</strong></p>
<figure class="highlight thrift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">namespace</span> java thrift.generated</span><br><span class="line"></span><br><span class="line"><span class="keyword">typedef</span> <span class="built_in">i16</span> short</span><br><span class="line"><span class="keyword">typedef</span> <span class="built_in">i32</span> int</span><br><span class="line"><span class="keyword">typedef</span> <span class="built_in">i64</span> long</span><br><span class="line"><span class="keyword">typedef</span> <span class="built_in">bool</span> boolean</span><br><span class="line"><span class="keyword">typedef</span> <span class="built_in">string</span> String</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">    <span class="number">1</span>: <span class="keyword">optional</span> String username,</span><br><span class="line">    <span class="number">2</span>: <span class="keyword">optional</span> int age,</span><br><span class="line">    <span class="number">3</span>: <span class="keyword">optional</span> boolean married</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">exception</span> <span class="title">DataException</span> </span>&#123;</span><br><span class="line">    <span class="number">1</span>: <span class="keyword">optional</span> String message,</span><br><span class="line">    <span class="number">2</span>: <span class="keyword">optional</span> String callStack,</span><br><span class="line">    <span class="number">3</span>: <span class="keyword">optional</span> String date</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">service</span> <span class="title">PersonService</span> </span>&#123;</span><br><span class="line">    Person getPersonByUsername(<span class="number">1</span>: <span class="keyword">required</span> String username) throws (<span class="number">1</span>: DataException dataException),</span><br><span class="line"></span><br><span class="line">    <span class="keyword">void</span> savePerson(<span class="number">1</span>: <span class="keyword">required</span> Person person) throws (<span class="number">1</span>: DataException dataException)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行生成代码命令</p>
<p><code>thrift --gen java src/thrift/data.thrift</code></p>
<p>记得导入<code>&#39;org.apache.thrift:libthrift:0.10.0&#39;</code></p>
<p>生成了3个类，分别是<code>Person</code>，<code>DataException</code>，<code>PersonService</code>。</p>
<p>然后我们来写一个service的实现类</p>
<p><code>PersonServiceImpl</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.sail.thrift;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> thrift.generated.DataException;</span><br><span class="line"><span class="keyword">import</span> thrift.generated.Person;</span><br><span class="line"><span class="keyword">import</span> thrift.generated.PersonService;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> yangfan</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2017/07/09</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PersonServiceImpl</span> <span class="keyword">implements</span> <span class="title">PersonService</span>.<span class="title">Iface</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Person <span class="title">getPersonByUsername</span><span class="params">(String username)</span> <span class="keyword">throws</span> DataException, org.apache.thrift.TException </span>&#123;</span><br><span class="line"></span><br><span class="line">        Person person = <span class="keyword">new</span> Person();</span><br><span class="line"></span><br><span class="line">        person.setUsername(username);</span><br><span class="line">        person.setAge(<span class="number">20</span>);</span><br><span class="line">        person.setMarried(<span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> person;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">savePerson</span><span class="params">(Person person)</span> <span class="keyword">throws</span> DataException, org.apache.thrift.TException </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Got Client Param: "</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(person.getUsername());</span><br><span class="line">        System.out.println(person.getAge());</span><br><span class="line">        System.out.println(person.isMarried());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h2><p>接下来编写客户端和服务端代码进行测试。</p>
<p><code>ThriftServer.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ThriftServer</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        TNonblockingServerSocket socket = <span class="keyword">new</span> TNonblockingServerSocket(<span class="number">8899</span>);</span><br><span class="line">        THsHaServer.Args arg = <span class="keyword">new</span> THsHaServer.Args(socket).minWorkerThreads(<span class="number">2</span>).maxWorkerThreads(<span class="number">4</span>);</span><br><span class="line">        PersonService.Processor&lt;PersonServiceImpl&gt; processor = <span class="keyword">new</span> PersonService.Processor&lt;&gt;(<span class="keyword">new</span> PersonServiceImpl());</span><br><span class="line"></span><br><span class="line">        arg.protocolFactory(<span class="keyword">new</span> TCompactProtocol.Factory());</span><br><span class="line">        arg.transportFactory(<span class="keyword">new</span> TFramedTransport.Factory());</span><br><span class="line">        arg.processorFactory(<span class="keyword">new</span> TProcessorFactory(processor));</span><br><span class="line"></span><br><span class="line">        TServer server = <span class="keyword">new</span> THsHaServer(arg);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">"Thrift Server Started"</span>);</span><br><span class="line"></span><br><span class="line">        server.serve();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>ThriftClient.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ThriftClient</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        TTransport transport = <span class="keyword">new</span> TFramedTransport(<span class="keyword">new</span> TSocket(<span class="string">"localhost"</span>, <span class="number">8899</span>), <span class="number">600</span>);</span><br><span class="line"></span><br><span class="line">        TProtocol protocol = <span class="keyword">new</span> TCompactProtocol(transport);</span><br><span class="line">        PersonService.Client client = <span class="keyword">new</span> PersonService.Client(protocol);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            transport.open();</span><br><span class="line"></span><br><span class="line">            Person person = client.getPersonByUsername(<span class="string">"张三"</span>);</span><br><span class="line"></span><br><span class="line">            System.out.println(person.getUsername());</span><br><span class="line">            System.out.println(person.getAge());</span><br><span class="line">            System.out.println(person.isMarried());</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">            Person person2 = <span class="keyword">new</span> Person();</span><br><span class="line">            person2.setUsername(<span class="string">"李四"</span>);</span><br><span class="line">            person2.setAge(<span class="number">30</span>);</span><br><span class="line">            person2.setMarried(<span class="keyword">true</span>);</span><br><span class="line"></span><br><span class="line">            client.savePerson(person2);</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(e.getMessage(), e);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            transport.close();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后分别启动服务端和客户端</p>
<p>服务端输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Thrift Server Started</span><br><span class="line">Got Client Param: </span><br><span class="line">李四</span><br><span class="line">30</span><br><span class="line">true</span><br></pre></td></tr></table></figure>
<p>客户端输出:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Received 1</span><br><span class="line">张三</span><br><span class="line">20</span><br><span class="line">false</span><br><span class="line">Received 2</span><br></pre></td></tr></table></figure>
<h2 id="Thrift传输格式"><a href="#Thrift传输格式" class="headerlink" title="Thrift传输格式"></a>Thrift传输格式</h2><ul>
<li>TBinaryProtocol-二进制格式</li>
<li>TCompactProtocal-压缩格式</li>
<li>TJSONProtocol-JSON格式</li>
<li>TSimpleJSONProtocol-提供JSON只写协议，生成的文件很容易通过脚本语言解析。</li>
<li>TDebugProtocol-使用易懂的可读的文本格式，以便于debug</li>
</ul>
<h2 id="Thrift数据传输方式"><a href="#Thrift数据传输方式" class="headerlink" title="Thrift数据传输方式"></a>Thrift数据传输方式</h2><ul>
<li>TSocket-阻塞式Socket</li>
<li>TFramedTransport-以frame为单位进行传输，非阻塞式服务中使用。</li>
<li>TFileTransport-以文件形式进行传输。</li>
<li>TMemortyTransport-将内存用于I/O，Java实现时内部实际使用了简单的ByteArrayOuputStream。</li>
<li>TZlibTransport-使用zlib进行压缩，与其他传输方式联合使用。当前无Java实现。</li>
</ul>
<h2 id="Thrift支持的服务模型"><a href="#Thrift支持的服务模型" class="headerlink" title="Thrift支持的服务模型"></a>Thrift支持的服务模型</h2><ul>
<li>TSimpleServer-简单的单线程服务模型，常用于测试</li>
<li>TThreadPoolServer-多线程服务模型，使用标准的阻塞式IO</li>
<li>TNonblockingServer-多线程服务模型，使用非阻塞式IO（需使用TFramedTransport数据传输方式）</li>
<li>THsHaServer-ThsHa引入了线程池去处理，其模型把读写任务房到线程池去处理；Half-sync/Half-async的处理模式，Half-aysnc是在处理IO时间上（accpect/read/write io），Half-sync是用于handler对rpc的同步处理</li>
</ul>
<h2 id="Thrift对多语言的支持"><a href="#Thrift对多语言的支持" class="headerlink" title="Thrift对多语言的支持"></a>Thrift对多语言的支持</h2><h3 id="Python作为Client"><a href="#Python作为Client" class="headerlink" title="Python作为Client"></a>Python作为Client</h3><p>在<code>data.thrift</code>中增加一行代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">namespace java thrift.generated</span><br><span class="line">namespace py py.thrift.generated</span><br></pre></td></tr></table></figure>
<p>然后执行命令生成python代码<br><code>thrift --gen py src/thrift/data.thrift</code></p>
<p>在Java项目中，我们的依赖是通过gradle引入的，这里python我们需要下载thrift的包，然后进入lib/py目录，执行里面的python脚本。</p>
<p><code>sudo python setup.py install</code></p>
<p>生成的依赖位于：<strong>/Library/Python/2.7/site-packages/thrift-0.10.0-py2.7-macosx-10.12-intel.egg</strong></p>
<p>然后编写客户端的代码</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding=utf-8</span></span><br><span class="line">__author__ = <span class="string">'sail'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> py.thrift.generated <span class="keyword">import</span> PersonService</span><br><span class="line"><span class="keyword">from</span> py.thrift.generated <span class="keyword">import</span> ttypes</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> thrift <span class="keyword">import</span> Thrift</span><br><span class="line"><span class="keyword">from</span> thrift.transport <span class="keyword">import</span> TSocket</span><br><span class="line"><span class="keyword">from</span> thrift.transport <span class="keyword">import</span> TTransport</span><br><span class="line"><span class="keyword">from</span> thrift.protocol <span class="keyword">import</span> TCompactProtocol</span><br><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"></span><br><span class="line">reload(sys)</span><br><span class="line">sys.setdefaultencoding(<span class="string">'utf8'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    tSocket = TSocket.TSocket(<span class="string">"localhost"</span>, <span class="number">8899</span>)</span><br><span class="line">    tSocket.setTimeout(<span class="number">600</span>)</span><br><span class="line"></span><br><span class="line">    transport = TTransport.TFramedTransport(tSocket)</span><br><span class="line">    protocol = TCompactProtocol.TCompactProtocol(transport)</span><br><span class="line">    client = PersonService.Client(protocol)</span><br><span class="line"></span><br><span class="line">    transport.open()</span><br><span class="line"></span><br><span class="line">    person = client.getPersonByUsername(<span class="string">"张三"</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">print</span> person.username</span><br><span class="line">    <span class="keyword">print</span> person.age</span><br><span class="line">    <span class="keyword">print</span> person.married</span><br><span class="line"></span><br><span class="line">    <span class="keyword">print</span> <span class="string">'----------------'</span></span><br><span class="line"></span><br><span class="line">    newPerson = ttypes.Person()</span><br><span class="line">    newPerson.username = <span class="string">"lisi"</span></span><br><span class="line">    newPerson.age = <span class="number">30</span></span><br><span class="line">    newPerson.married = <span class="keyword">True</span></span><br><span class="line"></span><br><span class="line">    client.savePerson(newPerson)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">except</span> Thrift.TException, tx:</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'%s'</span> % tx.message</span><br></pre></td></tr></table></figure>
<p>运行后输出以下结果</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">张三</span><br><span class="line">20</span><br><span class="line">False</span><br></pre></td></tr></table></figure>
<h3 id="Python作为Server"><a href="#Python作为Server" class="headerlink" title="Python作为Server"></a>Python作为Server</h3><p>编写<code>py_server.py</code>代码:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding=utf-8</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> py.thrift.generated <span class="keyword">import</span> PersonService</span><br><span class="line"><span class="keyword">from</span> PersonServiceImpl <span class="keyword">import</span> PersonServiceImpl</span><br><span class="line"><span class="keyword">from</span> thrift <span class="keyword">import</span> Thrift</span><br><span class="line"><span class="keyword">from</span> thrift.transport <span class="keyword">import</span> TTransport</span><br><span class="line"><span class="keyword">from</span> thrift.transport <span class="keyword">import</span> TSocket</span><br><span class="line"><span class="keyword">from</span> thrift.protocol <span class="keyword">import</span> TCompactProtocol</span><br><span class="line"><span class="keyword">from</span> thrift.server <span class="keyword">import</span> TServer</span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    personServiceHandler = PersonServiceImpl()</span><br><span class="line">    processor = PersonService.Processor(personServiceHandler)</span><br><span class="line"></span><br><span class="line">    serverSocket = TSocket.TServerSocket(port=<span class="number">8899</span>)</span><br><span class="line">    transportFactory = TTransport.TFramedTransportFactory()</span><br><span class="line">    protocolFactory = TCompactProtocol.TCompactProtocolFactory()</span><br><span class="line"></span><br><span class="line">    server = TServer.TSimpleServer(processor, serverSocket, transportFactory, protocolFactory)</span><br><span class="line">    server.serve()</span><br><span class="line"></span><br><span class="line"><span class="keyword">except</span> Thrift.TException, ex:</span><br><span class="line">    <span class="keyword">print</span> <span class="string">'%s'</span> % ex.message</span><br></pre></td></tr></table></figure>
<p>然后启动python的服务端，再分别执行Java和Python的客户端，都得到了正确的响应。</p>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/img/donate/wechatpay.jpeg" alt="杨帆 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/img/donate/alipay.jpeg" alt="杨帆 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/Netty/" rel="tag"># Netty</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/06/15/netty3/" rel="next" title="Netty-Google Protobuf介绍和使用">
                <i class="fa fa-chevron-left"></i> Netty-Google Protobuf介绍和使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/07/23/netty5/" rel="prev" title="Netty-gRPC介绍和使用">
                Netty-gRPC介绍和使用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yOTk2Ni82NTMx"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/img/photo/bug.png"
                alt="杨帆" />
            
              <p class="site-author-name" itemprop="name">杨帆</p>
              <p class="site-description motion-element" itemprop="description">记录工作和学习中遇到的问题</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">18</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">38</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sail-y" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/338632221" target="_blank" title="微博"><i class="fa fa-fw fa-globe"></i>微博</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Thrift"><span class="nav-number">1.</span> <span class="nav-text">Thrift</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Thrift数据类型"><span class="nav-number">1.1.</span> <span class="nav-text">Thrift数据类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Thrift容器类型"><span class="nav-number">1.2.</span> <span class="nav-text">Thrift容器类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Thrift工作原理"><span class="nav-number">1.3.</span> <span class="nav-text">Thrift工作原理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#结构体（struct）"><span class="nav-number">1.3.1.</span> <span class="nav-text">结构体（struct）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#枚举"><span class="nav-number">1.3.2.</span> <span class="nav-text">枚举</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#异常（exception）"><span class="nav-number">1.3.3.</span> <span class="nav-text">异常（exception）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#服务（service）"><span class="nav-number">1.3.4.</span> <span class="nav-text">服务（service）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#类型定义"><span class="nav-number">1.3.5.</span> <span class="nav-text">类型定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#常量（const）"><span class="nav-number">1.3.6.</span> <span class="nav-text">常量（const）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#命名空间"><span class="nav-number">1.3.7.</span> <span class="nav-text">命名空间</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#文件包含"><span class="nav-number">1.3.8.</span> <span class="nav-text">文件包含</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#注释"><span class="nav-number">1.3.9.</span> <span class="nav-text">注释</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#可选与必选"><span class="nav-number">1.3.10.</span> <span class="nav-text">可选与必选</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#生成代码"><span class="nav-number">1.3.11.</span> <span class="nav-text">生成代码</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#测试"><span class="nav-number">1.4.</span> <span class="nav-text">测试</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Thrift传输格式"><span class="nav-number">1.5.</span> <span class="nav-text">Thrift传输格式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Thrift数据传输方式"><span class="nav-number">1.6.</span> <span class="nav-text">Thrift数据传输方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Thrift支持的服务模型"><span class="nav-number">1.7.</span> <span class="nav-text">Thrift支持的服务模型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Thrift对多语言的支持"><span class="nav-number">1.8.</span> <span class="nav-text">Thrift对多语言的支持</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Python作为Client"><span class="nav-number">1.8.1.</span> <span class="nav-text">Python作为Client</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Python作为Server"><span class="nav-number">1.8.2.</span> <span class="nav-text">Python作为Server</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">杨帆</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Gemini</a> v6.1.0</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  



  
  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

</body>
</html>
